/*******************************************
 * Copyright 2007 Aphrodite Framework for javaME .
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Public License v2.0
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * Email : owner@aphroditeme.dev.java.net
 * Contributors:
 *     Kent Elton - initial API and implementation
 *******************************************/

package com.aphrodite.io.soap;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;

/**
 * Simple SOAP client used to call web services.
 * 
 * @author kentelt
 */
public class SoapClient {

	private static String userAgent = System.getProperty("microedition.platform") + " "
			+ System.getProperty("microedition.profiles") + "/" + System.getProperty("microedition.configuration");
	private SoapHandler handler;
	private SoapMessage message;

	private String url;

	public SoapClient(String url) {
		this.url = url;
	}

	public SoapClient(String url, SoapHandler handler, SoapMessage message) {
		this.url = url;
		this.handler = handler;
		this.message = message;
	}

	/**
	 * Executes the soap call of the soap message.
	 * 
	 * @throws IllegalStateException
	 *             If the SoapHandler or message is null
	 */
	public void call() {
		if (handler != null && message != null) {
			message.sealMessage();
			(new Thread() {
				public void run() {
					HttpConnection con = null;
					try {
						byte[] soapMessage = message.getSoapMessage();
						con = (HttpConnection) Connector.open(url);
						con.setRequestMethod(HttpConnection.POST);
						con.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
						con.setRequestProperty("User-Agent", userAgent);
						con.setRequestProperty("Content-Length", Integer.toString(soapMessage.length));
						con.setRequestProperty("SOAPAction", message.getRequestAction());
						OutputStream os = con.openOutputStream();
						os.write(soapMessage);
						InputStream is = con.openInputStream();
						if (is != null) {
							handler.handleResponse(is);
						}
						is.close();
						os.close();
						con.close();
					} catch (IOException e) {
						handler.handleError(e.toString());
					}
				}
			}).start();
		} else {
			throw new IllegalStateException("Soap Message not defined.");
		}
	}

	public void setSoapHandler(SoapHandler handler) {
		this.handler = handler;
	}

	public void setSoapMessage(SoapMessage message) {
		this.message = message;
	}

}
